<?php

/**
 * Process Quote Events
 * 
 * @category   CRM4Ecommerce
 * @package    CRM4Ecommerce_VtigerSynchronization
 * @author     Philip Nguyen <philip@crm4ecommerce.com>
 * @link       http://crm4ecommerce.com
 */
class CRM4Ecommerce_VtigerSynchronization_Model_Observer_Quote {

    /**
     * Synchronize Quote data after create new or update it
     *
     * @param Mage_Sales_Model_Quote $observer
     * @return CRM4Ecommerce_VtigerSynchronization_Model_Observer
     */
    public function saveAfter($observer) {
        if (!Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/general/status') ||
                !Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/synchronize_data/quote_synchronize_after_save'))
            return $this;
			
		if (Mage::getModel('core/session')->getRemoteSaveQuote() == '1') {
			return $this;
		}

        $serialkey = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/general/serial');
        $config = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/e');
        if ($config != base64_encode($serialkey . 'c2e26e257fdbb435b39cc022429b95b5') &&
                $config != base64_encode($serialkey . '4d4afda25a3f52041ee1b569157130b8') &&
                $config != base64_encode($serialkey . '94e94133f4bdc1794c6b647b8ea134d0')) {
            return $this;
        }

        $siteurl = Mage::getStoreConfig('web/unsecure/base_url');
        $siteurl = str_replace('/index.php/', '/', $siteurl);
        $siteurl = str_replace('/index.php', '/', $siteurl);
        if (($config == base64_encode($serialkey . '94e94133f4bdc1794c6b647b8ea134d0') || $config == base64_encode($serialkey . 'c2e26e257fdbb435b39cc022429b95b5')) &&
                Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/u') != sha1($siteurl)) {
            return $this;
        }

        $quote = null;
        if ($observer instanceof Mage_Sales_Model_Quote) {
            $quote = $observer;
        } else {
            $quote = $observer->getEvent()->getQuote();
        }
        if ((int) $quote->getCustomerId() == 0) {
            return $this;
        }

        if ($quote->getIsActive()) {
            if (Mage::getModel('core/session')->getQuoteCreatedNewItems()) {
                $quote = Mage::getModel('sales/quote')->load($quote->getId());
                Mage::getModel('core/session')->setQuoteCreatedNewItems(null);
                $quote->collectTotals()->save();
                return $this;
            }
            if ((Mage::getModel('core/session')->getQuoteCurrencyRate() == null || Mage::getModel('core/session')->getQuoteCurrencyRate() == '') && Mage::getSingleton('core/session')->getCartCurrencyCode() != $quote->getQuoteCurrencyCode()) {
                foreach ($quote->getAllItems() as $item) {
                    if ($item instanceof Mage_Sales_Model_Quote_Item) {
                        if (floatval($item->getCustomPrice()) > 0) {
                            $price = floatval($item->getCustomPrice());
                            $price = $price * ((float)$quote->getStoreToQuoteRate() / $quote->getVtigerCurrencyRate());
                            $item->setCustomPrice($price);
                            $item->setOriginalCustomPrice($price);
                            $item->calcRowTotal();
                            $item->calcTaxAmount();
                            $item->save();
                        }
                    }
                }
                Mage::getSingleton('core/session')->setCartCurrencyCode($quote->getQuoteCurrencyCode());
                $quote->collectTotals()->save();
                return $this;
            }

            if ((Mage::getSingleton('core/session')->getQuoteId() == $quote->getId())
                    && (Mage::getSingleton('core/session')->getQuoteGrandTotal() > 0 && Mage::getSingleton('core/session')->getQuoteGrandTotal() == $quote->getGrandTotal())
                    && (Mage::getSingleton('core/session')->getQuoteItemsQty() > 0 && Mage::getSingleton('core/session')->getQuoteItemsQty() == $quote->getItemsQty())
                    && (Mage::getSingleton('core/session')->getQuoteCouponCode() == $quote->getCouponCode())) {
                return $this;
            } else {
                if (Mage::getSingleton('core/session')->getQuoteGrandTotal() > 0 && Mage::getSingleton('core/session')->getQuoteGrandTotal() == $quote->getGrandTotal()) {
                    Mage::getSingleton('core/session')->setSyncPotential(false);
                } else {
                    Mage::getSingleton('core/session')->setSyncPotential(true);
                }
                Mage::getSingleton('core/session')->setQuoteId($quote->getId());
                Mage::getSingleton('core/session')->setQuoteGrandTotal($quote->getGrandTotal());
                Mage::getSingleton('core/session')->setQuoteItemsQty($quote->getItemsQty());
                Mage::getSingleton('core/session')->setQuoteCouponCode($quote->getCouponCode());
            }
        }
        $log = Mage::getModel('vtigersynchronization/log')
                ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::QUOTE)
                ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_INSTANTLY_AFTER_SAVE_OR_DELETE)
                ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::SAVE)
                ->setFromId($quote->getId())
                ->setToId($quote->getId())
        ;

        try {
            Mage::getModel('vtigersynchronization/synchronize_quote')->save($quote);
            $log->setStatus(true)
                    ->setNumberSuccess(1)
                    ->setSuccessIds($quote->getId())
                    ->setNumberFailure(0)
                    ->setFailureIds('')->addLogSuccess($quote->getId(), Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/quote_subject_prefix') . $quote->getId());
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            $error = Mage::helper('vtigersynchronization')->__('Error') . ": " . $e->getMessage() . "\n" . $e->getTraceAsString();
            $log->setStatus(false)
                    ->setNumberSuccess(0)
                    ->setSuccessIds('')
                    ->setNumberFailure(1)
                    ->setFailureIds($quote->getId())->addLogFailure($quote->getId(), Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/quote_subject_prefix') . $quote->getId(), $error);
        }
        $log->save();

        return $this;
    }

    /**
     * Delete Quote
     *
     * @param Mage_Sales_Model_Quote $observer
     * @return CRM4Ecommerce_VtigerSynchronization_Model_Observer
     */
    public function deleteAfter($observer) {
        if (!Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/general/status') ||
                !Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/synchronize_data/quote_synchronize_after_save'))
            return $this;

        $serialkey = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/general/serial');
        $config = Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/e');
        if ($config != base64_encode($serialkey . 'c2e26e257fdbb435b39cc022429b95b5') &&
                $config != base64_encode($serialkey . '4d4afda25a3f52041ee1b569157130b8') &&
                $config != base64_encode($serialkey . '94e94133f4bdc1794c6b647b8ea134d0')) {
            return $this;
        }

        $siteurl = Mage::getStoreConfig('web/unsecure/base_url');
        $siteurl = str_replace('/index.php/', '/', $siteurl);
        $siteurl = str_replace('/index.php', '/', $siteurl);
        if (($config == base64_encode($serialkey . '94e94133f4bdc1794c6b647b8ea134d0') || $config == base64_encode($serialkey . 'c2e26e257fdbb435b39cc022429b95b5')) &&
                Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/u') != sha1($siteurl)) {
            return $this;
        }

        $quote = null;
        if ($observer instanceof Mage_Sales_Model_Quote) {
            $quote = $observer;
        } else {
            $quote = $observer->getEvent()->getQuote();
        }
        if ((int) $quote->getCustomerId() == 0 || (int) $quote->getItemsQty() == 0) {
            return $this;
        }

        $log = Mage::getModel('vtigersynchronization/log')
                ->setTypeData(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogDataType::QUOTE)
                ->setMode(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogMode::LOG_INSTANTLY_AFTER_SAVE_OR_DELETE)
                ->setAction(CRM4Ecommerce_VtigerSynchronization_Model_Array_LogAction::DELETE)
                ->setFromId($quote->getId())
                ->setToId($quote->getId())
        ;

        try {
            Mage::getModel('vtigersynchronization/synchronize_quote')->delete($quote);
            $log->setStatus(true)
                    ->setNumberSuccess(1)
                    ->setSuccessIds($quote->getId())
                    ->setNumberFailure(0)
                    ->setFailureIds('')
                    ->addLogSuccess($quote->getId(), Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/quote_subject_prefix') . $quote->getId());
        } catch (Exception $e) {
            Mage::getSingleton('adminhtml/session')->addError($e->getMessage());
            $error = Mage::helper('vtigersynchronization')->__('Error') . ": " . $e->getMessage() . "\n" . $e->getTraceAsString();
            $log->setStatus(false)
                    ->setNumberSuccess(0)
                    ->setSuccessIds('')
                    ->setNumberFailure(1)
                    ->setFailureIds($quote->getId())
                    ->addLogFailure($quote->getId(), Mage::getStoreConfig('crm4ecommerce_vtigersynchronization/sales_params_settings/quote_subject_prefix') . $quote->getId(), $error);
        }
        $log->save();

        return $this;
    }

}